#ifndef __COMM_HPP__
#define __COMM_HPP__

#include"log.hpp"
#include<iostream>
#include<string>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h> 
#include<sys/types.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ipc.h>

using namespace std;

const int Size = 4096;
const string pathname = "/home/xyx";
const int proj_id = 0x6666;

Log log;

key_t getKey()
{
    key_t k = ftok(pathname.c_str(),proj_id);
    if(k < 0)
    {
        log(Fatal,"ftok error : %s \n",strerror(errno));
        exit(1);
    }
    log(Info,"ftok success, key is :%0x%x",k);
    return k;
}

int getShareMemHelper(int flag)
{
    key_t k = getKey();
    int shmid = shmget(k,Size,flag);
    if(shmid < 0)
    {
        log(Fatal,"shmget fail : %s\n",strerror(errno));
        exit(2);
    }
    log(Info,"shmget success, shmid is :%d",shmid );
    return shmid;
}

int createShm()
{
    return getShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

int getShm()
{
    return getShareMemHelper(IPC_CREAT);
}
#define FIFO_FILE "./myfifo"
#define MODE 0664

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
};

class Init
{
public:
    Init()
    {
    //创建信道
        int n = mkfifo(FIFO_FILE,MODE);
        if(n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
    //删除信道
        int m = unlink(FIFO_FILE);
        if(m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};
#endif